package com.zkny.zknyerp.config;

import com.zkny.zknyerp.model.User;
import com.zkny.zknyerp.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

public class UserRealms extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}
	
	//实现登录认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//token为前端传过来的令牌
		//前端请求到达后端，直接认证，若身份为空，抛异常
		if(ObjectUtils.isEmpty(token.getPrincipal())) {
			return null;
		}
		//获取前端传过来的用户信息
		String username = (String)token.getPrincipal();
		//数据库获取管理员信息
		User user = userService.queryUser(username);
		if(!ObjectUtils.isEmpty(user)) {
			//匹配密码
			//参数1前端传用户身份
			//参数2数据库中查到的密码
			//参数3加密盐
			//参数4当前类名
			//处理加密盐
			ByteSource credentialsSalt = ByteSource.Util.bytes(username);
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt , getName());
			return info;
		}
		return null;
	}

}
